'use strict';

import Base from './base.js';
import pagination from 'think-pagination';//引入分页插件

export default class extends Base {

  init(http) {
    super.init(http);
  }

  //后台主界面
  async indexAction() {
    //分页
    let where = 'is_publish = 1';
    if (this.get('key')) {
      let k = this.get('key');
      where += " and title like '%" + k + "%' or email like '%" + k + "%'";
      this.assign('key', k);
    }
    let dataList = await this.model('guestbook').dataList(where, this.get('page'), 10);
    let pageBar = pagination(dataList, this.http, {});//实例化分页
    //this.end(dataList);
    //return false;
    let totalGuest = await this.model('guestbook').total(where);

    this.assign('dataList', dataList.data);
    this.assign('pageBar', pageBar);//传入数据
    this.assign('totalGuest', totalGuest);
    return this.display('admin/guestbook/mailbox');
  }

  //详情
  async detailAction() {
    if (!this.get('id')) {
      error('参数错误', this.http);
    }
    let where = 'id = ' + this.get('id');
    let data = await this.model('guestbook').where(where).find();
    //this.end(data);
    if (think.isEmpty(data)) {
      error('该信息可能已被删除', this.http);
    }
    this.assign('data', data);
    return this.display('admin/guestbook/mail_detail')
  }

  //留言回复
  async replyAction() {
    let post = this.post();
    //转实体
    let reply = htmlencode(post.reply);
    //保存
    let obj = await this.model('guestbook').where('id ='+post.id).update({reply:reply,readed:1});
    if (obj) {
      this.success('', '处理成功');
    } else {
      this.fail(2,'保存失败');
    }
  }
}